<template>
  <div class="root">
    <el-tabs tab-position="left" v-model="tabs.active" @tab-click="tabFn">
      <el-tab-pane
        :label="val.name"
        :name="val.value"
        v-for="(val, ind) in tabs.list"
        :key="ind"
      >
        <div class="flex c10">
          <configAdd :data="tabs.list[tabs.index]" @reload="getList()" />
          <el-popover
            placement="bottom"
            title="配置项使用说明"
            width="750px"
            trigger="click"
          >
            <template #reference>
              <el-button style="margin-left: 10px">配置项使用说明</el-button>
            </template>
            <div class="config-tips">
              <img src="@/assets/2024092801.png" />
              <div>
                1、除了【个性化页面配置】，其他配置项可以直接在网站html页面中使用<span>&lt;div&gt;{$c['key_name']}&lt;/div&gt;</span>获取
              </div>
              <div>
                2、所有配置项可以通过php使用<span
                  >$data = $this->formatConfig('key_name');</span
                >获取
              </div>
              <div>
                3、所有配置项可以通过ajax请求<span>$.getJSON('/index/tools/getConfig?key=key_name');</span>获取
              </div>
              <div>
                4、配置项内有多条数据的，当鼠标出现十字图标的时候，可以进行拖拽排序
              </div>
            </div>
          </el-popover>
          <getColor/>
        </div>
        <el-scrollbar height="calc(100vh - 150px)" v-loading="pData.loading">
          <div
            class="c1 page-bg"
            v-for="(item, listIndex) in pData.list"
            :key="item.id"
          >
            <div class="c2 flex">
              <!-- 标题 -->
              <div class="c3 flex">
                <div class="b1">{{ item.title }}</div>
                <div>{{ item.key }}</div>
              </div>
              <!-- 操作 -->
              <div class="c4">
                <el-button
                  v-if="item.arr == 'y'"
                  @click="addConfig(item, listIndex)"
                  >新增{{ item.title }}</el-button
                >
                <el-button
                  type="primary"
                  @click="saveFn(item)"
                  v-if="item.data_type != 'editor'"
                  >保存修改</el-button
                >
                <el-button type="danger" @click="delFn(item)">删除</el-button>
                <dataStructure :item="item" @save="saveFn" />
              </div>
            </div>

            <div class="c3">
              <!-- 内容数组 -->
              <draggable
                v-if="item.arr == 'y'"
                tag="transition-group"
                :component-data="{
                  tag: 'div',
                  type: 'transition-group',
                  name: !drag ? 'flip-list' : null,
                }"
                :list="item.value"
                v-bind="dragOptions"
                @start="drag = true"
                @end="drag = false"
                item-key="id"
              >
                <template #item="{ element, index }">
                  <diy
                    :type="item.data_type"
                    :data="element"
                    isArr
                    @remove="removeOne(item.value, index)"
                    @pickImg="pickImg(item.key, listIndex, index, $event)"
                  />
                </template>
              </draggable>

              <!-- 非数组 -->
              <diy
                v-else
                :type="item.data_type"
                :data="item"
                :isArr="false"
                @pickImg="pickImg(item.key, listIndex, $event)"
                @openEditor="openEditor(item)"
              />
              <div class="tips">{{ item.notes }}</div>
            </div>
          </div>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>

    <!-- 富文本编辑弹窗 -->
    <el-dialog
      v-model="editorData.show"
      :title="editorData.data?.title"
      width="88%"
      top="5vh"
      destroy-on-close
    >
      <editor ref="editorRef" @selectImg="pickImg('editor')" />
      <template #footer>
        <el-button type="primary" @click="saveEditorFn()">保存更改</el-button>
        <el-button @click="editorData.show = false">取消编辑</el-button>
      </template>
    </el-dialog>

    <!-- 图片选择弹窗 -->
    <layerImg v-model="imgOption.show" @getImg="getImg" />
  </div>
</template>
<script lang="ts" setup>
import { editor } from "@/components/editPage";
import diy from "./components/diy.vue";
import configAdd from "./components/configAdd.vue";
import dataStructure from "./components/dataStructure.vue";
import getColor from "./components/getColor.vue";
import type { TabsPaneContext } from "element-plus";
import { post } from "@/common/http";
import { layerImg, useImgHook } from "@/components/formImg";
import config from "@/common/config";
import { ElMessage, ElMessageBox } from "element-plus";
import draggable from "vuedraggable"; //拖拽组件配置信息
const drag = ref(false);
const dragOptions = computed(() => {
  return {
    animation: 200,
    group: "description",
    disabled: false,
    ghostClass: "ghost",
  };
});

const tabs = reactive({
  active: sessionStorage.getItem("configTabName") || "web_config",
  index: 0,
  list: [
    { name: "网站配置", value: "web_config" },
    { name: "企业信息", value: "company" },
    { name: "公共页面SEO", value: "web_seo" },
    { name: "个性化页面配置", value: "web_diy" },
    { name: "其他配置", value: "other" },
  ],
});
function tabFn(tab: TabsPaneContext) {
  tabs.index = Number(tab.index);
  sessionStorage.setItem("configTabName", tabs.list[tabs.index].value);
  nextTick(() => {
    getList();
  });
}

onMounted(() => {
  getList();
});

const pData = reactive<any>({
  list: [],
  loading: true,
});

//获取当前tabIndex栏配置
function getList() {
  pData.loading = true;
  post("api/Config/getConfigTabs", {
    type: tabs.active,
  }).then((res) => {
    pData.loading = false;
    pData.list = [];
    pData.list = res.data;
    imgKeyName = res.data.map((v: any) => v.key);
  });
}

const { imgOption, pickImg } = useImgHook();

let imgKeyName: string[] = [];

//获取弹窗选择的图片
function getImg(data: any) {
  let { name, index, index1, index2 } = imgOption.option;
  if (imgKeyName.includes(name)) {
    //根据是否存index2数组下标来判断数据是单图 还是 多图结构
    if (index2 == -1) {
      //判断是第一张图片操作 还是 第二张图片操作
      if (index1 === 1) {
        pData.list[index].value.img = data.imgUrl;
      } else {
        pData.list[index].value.img1 = data.imgUrl;
      }
    } else {
      //判断是第一张图片操作 还是 第二张图片操作
      if (index2 === 1) {
        pData.list[index].value[index1].img = data.imgUrl;
      } else {
        pData.list[index].value[index1].img1 = data.imgUrl;
      }
    }
  }

  //编辑器图片上传
  if (name === "editor") {
    //编辑器选择图片
    editorRef.value.editorObj.execCommand(
      "inserthtml",
      `<p><img style='max-width:100%' src='${
        config.serverImg + data.imgUrl
      }'/></p>`
    );
  }
}

const editorRef = ref();
const editorData = reactive<any>({
  show: false,
  data: null,
});

//打开富文本弹窗
function openEditor(data: any) {
  editorData.show = true;
  editorData.data = data;
  nextTick(() => {
    editorRef.value.content = data.value;
  });
}
//保存富文本编辑
function saveEditorFn() {
  editorData.data.value = editorRef.value.content;
  saveFn(editorData.data);
  editorData.show = false;
}

//保存修改
function saveFn(data: any) {
  data = JSON.parse(JSON.stringify(data));
  if (data.arr == "y" || data.data_type == "img") {
    data.value = JSON.stringify(data.value);
  }
  post("api/Config/saveConfig", data).then((res) => {
    ElMessage.success("保存成功");
    getList();
  });
}

//新增配置
function addConfig(data: any, index: number) {
  let obj = {};
  if (data.data_type === "imgs") obj = { img: "", text: "", other: "" };
  if (data.data_type === "keyVal") obj = { key: "", val: "" };
  if (data.data_type === "color") obj = { value: "" };
  pData.list[index].value.unshift(obj);
}

//删除配置
function delFn(data: any) {
  ElMessageBox.alert(
    `如果页面中有使用当前配置项，会导致页面异常<br/>确定删除配置项:<strong>${data.title}<strong>`,
    "系统提示",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      callback: (action: string) => {
        console.log(action);
        if (action != "cancel") {
          return ElMessage.warning("效果预览模式，不能删除哦！");
          post("api/Config/del_config", {
            id: data.id,
          }).then((res) => {
            ElMessage.success("删除成功");
            getList();
          });
        }
      },
    }
  );
}

//移除配置中的某一项
function removeOne(data: any, index: number) {
  if (data.length > 1) {
    data.splice(index, 1);
  } else {
    ElMessage.warning("删除失败，最少保留一个");
  }
}
</script>

<style scoped lang="scss">
.root {
  padding: 5px 0 0 0;
  .el-scrollbar {
    padding: 0 10px 0 10px;
  }
  .c1 {
    margin-bottom: 10px;
    padding: 5px;
    align-items: flex-start;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .c2 {
    justify-content: space-between;
    padding: 0 5px;
    .b1 {
      margin-right: 10px;
      font-size: 14px;
    }
  }
  .c3 {
    font-size: 13px;
    div:last-child {
      color: #888;
      font-size: 12px;
      margin-top: 2px;
    }
    .tips {
      padding: 0 10px;
    }
  }
  .c5 {
    width: 100%;
    text-align: left;
    padding: 5px 35px;
    .el-button {
      font-size: 13px;
    }
  }
  .c6 {
    flex: 1;
  }

  .c10 {
    margin: 0 0 10px 10px;
    .b2 {
      margin-left: 10px;
    }
  }
}

.config-tips {
  line-height: 30px;
  span {
    color: var(--el-color-primary);
  }
}
@media screen and (max-width: 1400px) {
  .root {
    .c4 {
      padding: 5px 15px;
    }
  }
}
</style>
